<template>
  <div class="create-classroom">
    <div class="header">
      <span>创建课堂</span>
      <el-button type="text" class="header-btn" @click="goBack">返回</el-button>
    </div>

    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="demo-form">
      <el-form-item label="课程名称" prop="Cname">
        <el-input v-model="form.Cname" placeholder="例如：计算机网络"></el-input>
      </el-form-item>

      <el-form-item label="课程班级" prop="name">
        <el-input v-model="form.name" placeholder="例如：计算机网络2025春"></el-input>
      </el-form-item>

      <el-form-item label="总学时" prop="hours">
        <el-input v-model.number="form.hours" type="number" placeholder="例如：32"></el-input>
      </el-form-item>

      <el-form-item label="学分" prop="credits">
        <el-input v-model.number="form.credits" type="number" placeholder="例如：4.0"></el-input>
      </el-form-item>

      <el-form-item label="结束时间" prop="end_time">
        <el-date-picker
          v-model="form.end_time"
          type="datetime"
          placeholder="请选择结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="课程模块">
        <el-checkbox-group v-model="form.module">
          <el-checkbox v-for="mod in modules" :key="mod" :label="mod"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="公开状态">
        <el-select v-model="form.open_status" placeholder="请选择公开状态">
          <el-option label="不公开" :value="0"></el-option>
          <el-option label="公开" :value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属院系" prop="depart">
        <el-input v-model="form.depart" placeholder="例如：计算机科学与技术"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="js">
import axios from "axios";

export default {
  name: "CreateClassroom",
  data() {
    return {
      form: {
        Cname: "",
        name: "",
        hours: null,
        credits: null,
        end_time: null,
        module: [],
        open_status: null,
        depart: "",
      },
      modules: ["通知公告", "课程设计", "知识图谱", "课堂分班", "平时作业", "在线考试", "工程认证", "课程资源", "数据统计"],
      rules: {
        Cname: [
          {required: true, message: "请输入课程名称", trigger: "blur"},
          {max: 60, message: "课程名称不能超过60个字符", trigger: "blur"},
        ],
        name: [
          {required: true, message: "请输入课程班级", trigger: "blur"},
          {max: 60, message: "课程班级不能超过60个字符", trigger: "blur"},
        ],
        hours: [
          {required: true, message: "请输入总学时", trigger: "blur"},
          {type: "number", min: 1, message: "学时必须大于0", trigger: "blur"},
        ],
        credits: [
          {required: true, message: "请输入学分", trigger: "blur"},
          {type: "number", min: 1, message: "学分必须大于0", trigger: "blur"},
        ],
        end_time: [{required: true, message: "请选择结束时间", trigger: "change"}],
        depart: [{required: true, message: "请输入所属院系", trigger: "blur"}],
      },
    };
  },
  methods: {
    goBack() {
      this.$router.push("/");
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const courseData = new URLSearchParams();

          // 遍历表单数据，将其转换为 URL 编码格式
          for (const key in this.form) {
            if (key === "module") {
              // module 需要转换成 JSON 字符串
              courseData.append(key, JSON.stringify(this.form[key]));
            } else {
              courseData.append(key, this.form[key]);
            }
          }

          try {
            const response = await axios.post("course/teachingClass/createTeachingClass", courseData, {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            });

            if (response.status === 200 && response.data.code === "200") {
              this.$message.success("创建课程成功！");
              // 使用课程名称 name 进行跳转，而不是 courseId
              this.$router.push({
                name: "CoursePage",
                query: { name: this.form.name }
              });
            } else {
              this.$message.error("创建课程失败：" + response.data.message);
            }
          } catch (error) {
            this.$message.error("创建课程失败，请检查后端接口！");
            console.error(error);
          }
        } else {
          this.$message.warning("请检查表单填写是否正确");
        }
      });
    },
  },
};
</script>

<style scoped>
.create-classroom {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 20px 40px;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 800px;
  margin-bottom: 20px;
}

.header-btn {
  font-size: 14px;
  cursor: pointer;
}

.demo-form {
  width: 100%;
  max-width: 800px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 30px;
}

.el-input,
.el-date-picker,
.el-select {
  width: 100%;
}
</style>
